﻿using Assets.Core.Common.Web;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Nucleic.Core.DoMain;
using Nucleic.Core;
using Nucleic.Core.Utils;
using Nucleic.Core.Utils.hebcz;
using Senparc.CO2NET.Extensions;
using Senparc.Weixin;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.AdvancedAPIs.OAuth;
using System.Net;
using YinLong.Tool.Net.HttpHelperMin;

namespace Nucleic.Web.Controllers
{
    public class WeiXinController : Controller
    {
        private readonly ILogger<BankController> _logger;

        public WeiXinController(ILogger<BankController> logger)
        {
            _logger = logger;

        }
        public IActionResult paynotice()
        {
            _logger.LogInformation($"建行回调[paynotice]->paynotice---------开始------------");

            var keys = Request.Form.Keys;

            Dictionary<string, string> json = new Dictionary<string, string>();
            foreach (var item in keys)
            {
                string value = Request.Form[item].ToString();
                json.Add(item, value);
            }
            keys = Request.Query.Keys;
            foreach (var item in keys)
            {
                string value = Request.Query[item].ToString();
                json.Add(item, value);
            }
            _logger.LogInformation($"建行回调[paynotice]->" + JsonConvert.SerializeObject(json));

            //通过建行返回报文中得单号获取订单模型
            var orders_id = json["ORDERID"];

            var dt = DateTime.Now;
            var book = SqlSugarFactory.Instance.Queryable<book_info>().First(i => i.orders_id == orders_id);

            if (book != null && book.status == "0")
            {
                var patient = SqlSugarFactory.Instance.Queryable<patient_info>().First(x => x.pat_id == book.pat_id);
                //如果确实为这个订单
                if (patient != null && json["REMARK1"] == patient.idnum && json["SUCCESS"] == "Y")
                {
                    _logger.LogInformation($"建行回调[paynotice]->更新预约状态订单状态");

                    //修改预约状态
                    book.status = "1";
                    book.update_time = dt;
                    SqlSugarFactory.Instance.Updateable(book).ExecuteCommand();

                    var item = SqlSugarFactory.Instance.Queryable<check_item>().First(i => i.item_id == book.item_id);
                    var itemtype = SqlSugarFactory.Instance.Queryable<check_type>().First(i => i.item_id == book.item_id);

                    //新增订单状态
                    order_info order_ = SqlSugarFactory.Instance.Queryable<order_info>().First(x => x.orders_id == book.orders_id);
                    if (order_ == null)
                    {
                        order_ = new order_info
                        {
                            pay_time = dt,
                            pat_id = book.pat_id,
                            appo_id = book.appo_id,
                            item_id = book.item_id,
                            price = item.price,
                            num = itemtype.num,
                            orders_id = book.orders_id,
                            wx_order_no = "建行",
                            status = "0",
                            invoiceStatus = 0
                        };
                        if (patient != null)
                        {
                            order_.tel = patient.tel;
                            order_.idnum = patient.idnum;
                            order_.pat_name = patient.name;
                        }
                        SqlSugarFactory.Instance.Insertable<order_info>(order_).ExecuteCommand();
                        _logger.LogInformation($"[{orders_id}]->充值成功->写入数据库");
                    }


                    //申请电子发票

                    _logger.LogInformation($"[{orders_id}]->充值成功->申请发票");

                    mkomedicaleinvoiceModel model = new mkomedicaleinvoiceModel()
                    {
                        einvoicespecimen = "1",
                        issuedate = dt.ToString("yyyyMMdd"),
                        issuetime = dt.ToString("hh:mm:ss"),
                        payerpartytype = "1",
                        payerpartyname = patient.name,
                        totalamount = double.Parse(item.price.ToString()).ToString(),
                        bizcode = orders_id,
                        handlingperson = hebczConst.handlingperson,
                        checker = hebczConst.checker,
                        fundpayamount = "0",
                        otherpayamount = "0",
                        accountpayamount = "0",
                        ownpayamount = double.Parse(item.price.ToString()).ToString(),
                        //relatedinvoicecode = "1253",
                        //relatedinvoicenumber = orders_id,
                    };
                    model.details.Add(new details
                    {
                        itemcode = hebczConst.item_code,
                        itemname = hebczConst.item_name,
                        itemamount = double.Parse(item.price.ToString()).ToString(),

                    });
                    model.auxdetails.Add(new auxdetails
                    {
                        auxitemrelatedcode = hebczConst.item_code,
                        auxitemrelatedname = hebczConst.item_name,
                        auxitemname = item.name,
                        auxitemamount = double.Parse(item.price.ToString()).ToString()
                    });
                    HttpHelperMin http = new HttpHelperMin();
                    HttpItemMin httpitem = new HttpItemMin()
                    {
                        URL = hebczConst.Url + "/mkomedicaleinvoice",
                        Method = "POST",
                        ContentType = "application/json",
                        Postdata = JsonConvert.SerializeObject(model),
                    };
                    var resule = http.GetHtml(httpitem);
                    _logger.LogInformation($"[{orders_id}]->充值成功->申请发票返回:" + resule.Html);

                    var invStatus = JsonConvert.DeserializeObject<ReturnData<MeInvoiceStatusDto>>(resule.Html);
                    if (invStatus != null && invStatus.code == 1)
                    {
                        //查询开票状态
                        invStatus = hebczUtil.invoicestatus(orders_id);
                        _logger.LogInformation($"[{orders_id}]->充值成功->查询发票状态:" + JsonConvert.SerializeObject(invStatus));
                        //如果没有获取过，申请电子发票
                        if (invStatus != null && invStatus.code == 1 && invStatus.data.Count > 0 && invStatus.data[0].state != "0")
                        {
                            order_.einvoicecode = invStatus.data[0].einvoicecode;
                            order_.einvoicenumber = invStatus.data[0].einvoicenumber;
                            order_.randomnumber = invStatus.data[0].randomnumber;
                            order_.invoiceStatus = 1;
                            SqlSugarFactory.Instance.Updateable(order_).ExecuteCommand();
                        }

                    }


                }
            }
            return null;
        }
        /// <summary>
        /// 微信签名
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        [Route("GetSignature")]
        [HttpPost]
        public IActionResult GetSignature(string url)
        {
            var appid = ConfigurationUtil.GetSection("Bank:WeixinAppId");
            var appSecret = ConfigurationUtil.GetSection("Bank:WeixinAppSecret");
            string timpstamp = WeiXinUtil.CreateTimestamp();
            string nonceStr = WeiXinUtil.CreateNonceStr();
            string sig = WeiXinUtil.GetSignature(timpstamp, nonceStr, url, appid, appSecret);
            return Content(Newtonsoft.Json.JsonConvert.SerializeObject(Result.success(new { sig, timpstamp, nonceStr })));
        }
        [HttpPost]
        [Route("GetAuthorizeUrl")]
        public IActionResult GetAuthorizeUrl()
        {
            var appid = ConfigurationUtil.GetSection("WeChatPay:AppId");
            var returnUrl = ConfigurationUtil.GetSection("WeChatPay:ReturnUrl");

            var callBack = OAuthApi.GetAuthorizeUrl(appid,
                 "http://sdk.weixin.senparc.com/oauth2/BaseCallback?returnUrl=" + returnUrl.UrlEncode(),

                 null, OAuthScope.snsapi_base);//snsapi_base方式回调地址
            return Content(callBack);
        }
        
        /// <summary>
        /// getcode的地址必须在网页授权域名里,获取openid的程序在那里服务器
        /// </summary>
        /// <param name="code"></param>
        /// <param name="returnUrl">用户最初尝试进入的页面</param>
        /// <returns></returns>
        [HttpPost]
        [Route("GetOpenId")]
        public IActionResult GetOpenId(string code, string returnUrl)
        {
            //https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx32c0dfcb4dc3fc23&redirect_uri=http://www.tssdeyy.com/Order/C_Home&response_type=code&scope=snsapi_base&state=123&connect_redirect=1#wechat_redirect
            if (string.IsNullOrEmpty(code))
            {
                return Content(Newtonsoft.Json.JsonConvert.SerializeObject(Result.fail("您拒绝了授权！")));
            }
            OAuthAccessTokenResult result = null;
            //通过，用code换取access_token
            //var appid = ConfigurationUtil.GetSection("WeChatPay:AppId");
            //var appSecret = ConfigurationUtil.GetSection("WeChatPay:APIKey");

            var appid = ConfigurationUtil.GetSection("Bank:WeixinAppId");
            var appSecret = ConfigurationUtil.GetSection("Bank:WeixinAppSecret");
            string rMsg = string.Empty;
            HttpWebRequest httpRequest = null;
            HttpWebResponse httpResponse = null;
            try
            {
                httpRequest =
                       WebRequest.Create(
                               $"https://api.weixin.qq.com/sns/oauth2/access_token?appid={appid}&secret={appSecret}&code={code}&grant_type=authorization_code")
                        as HttpWebRequest;
                httpRequest.Method = "GET";
                httpRequest.ContentType = "text/html";
                //接收响应数据
                httpResponse = httpRequest.GetResponse() as HttpWebResponse;
                StreamReader reader = new StreamReader(httpResponse.GetResponseStream(),
                        System.Text.Encoding.GetEncoding("UTF-8"));
                if (httpResponse.StatusCode == HttpStatusCode.OK)
                {
                    rMsg = reader.ReadToEnd();
                    reader.Dispose();
                }
            }
            catch (Exception e)
            {

                return Content("网络异常:" + e.Message);
            }
            finally
            {
                httpRequest = null;
                httpResponse = null;
            }
            var m = Newtonsoft.Json.JsonConvert.DeserializeObject<wxcodecs>(rMsg);
            if (string.IsNullOrWhiteSpace(rMsg))
            {
                return Content("无法获取openid");
            }
            if (string.IsNullOrWhiteSpace(m.openid))
            {
                return Content("微信异常:" + rMsg);
            }

            return Content(m.openid);
            //try
            //{
            //    result = OAuthApi.GetAccessToken(appid, appSecret, code);
            //}
            //catch (Exception ex)
            //{
            //    return Content(Newtonsoft.Json.JsonConvert.SerializeObject(Result.fail(ex.Message)));
            //}
            //if (result.errcode != ReturnCode.请求成功)
            //{
            //    return Content(Newtonsoft.Json.JsonConvert.SerializeObject(Result.fail("错误：" + result.errmsg)));
            //}

            //return Content(Newtonsoft.Json.JsonConvert.SerializeObject(Result.success(result.openid)));
        }
    }
    public class wxcodecs
    {
        public string access_token { get; set; }

        public string refresh_token { get; set; }

        public string openid { get; set; }

        public long expires_in { get; set; }

        public string scope { get; set; }
    }
}